package com.atguigu.gmall.cart.service;

import com.alibaba.fastjson.JSON;
import com.atguigu.core.bean.Resp;
import com.atguigu.gmall.cart.fegin.GmallPmsClient;
import com.atguigu.gmall.cart.fegin.GmallSmsClient;
import com.atguigu.gmall.cart.fegin.GmallWmsClient;
import com.atguigu.gmall.cart.interceptors.LoginInterceptor;
import com.atguigu.gmall.cart.pojo.Cart;
import com.atguigu.gmall.cart.pojo.UserInfo;
import com.atguigu.gmall.pms.entity.SkuInfoEntity;
import com.atguigu.gmall.pms.entity.SkuSaleAttrValueEntity;
import com.atguigu.gmall.sms.vo.ItemSkuSaleVO;
import com.atguigu.gmall.wms.entity.WareSkuEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import springfox.documentation.spring.web.json.Json;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartService {

    @Autowired
    private GmallPmsClient gmallPmsClient;

    @Autowired
    private GmallWmsClient gmallWmsClient;
    @Autowired
    private GmallSmsClient gmallSmsClient;
    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String CART_PREFIX = "cart:uid:";

    private static final String CURRENT_PRICE_PREFIX = "cart:price:";
    /**
     * 添加购物车的业务
     * @param cart
     */
    public void addCart(Cart cart) {

        String key=CART_PREFIX;

        //获取登录状态
        UserInfo userInfo = LoginInterceptor.getUserInfo();
        if(userInfo.getId()!=null){
            key+=userInfo.getId();
        }else{
            key+=userInfo.getUserKey();
        }

        //获取购物车,获取的是用户Hash操作对象
        BoundHashOperations<String, Object, Object> hashOps= this.redisTemplate.boundHashOps(key);
        //判断购物车有无该记录，有的话更新，没有的话新增购物车
        // 注意这里的skuId要转化成String，因为redis中保存的都是String
        Long skuId = cart.getSkuId();
        Integer count = cart.getCount();
        if(hashOps.hasKey(skuId.toString())){
            //通过skuId判断，有修改
            //获取购物车中的Sku记录
            String castJson = hashOps.get(skuId.toString()).toString();
            //反序列化
            cart = JSON.parseObject(castJson, Cart.class);
            //修改数量
            cart.setCount(cart.getCount()+count);

        }else{
            // 购物车不存在该记录，新增记录
            cart.setCheck(true);
            //查询sku相关信息
            Resp<SkuInfoEntity> skuResp = this.gmallPmsClient.querySkuBySkuId(skuId);
            SkuInfoEntity skuInfoEntity = skuResp.getData();
            if(skuInfoEntity==null){
                return ;
            }
            cart.setCount(count);
            cart.setDefaultImgage(skuInfoEntity.getSkuDefaultImg());
            cart.setPrice(skuInfoEntity.getPrice());
            cart.setTitle(skuInfoEntity.getSkuTitle());

            //查询营销属性
            Resp<List<SkuSaleAttrValueEntity>> saleAttrValueResp = this.gmallPmsClient.querySkuSaleAttrValueBySkuId(skuId);
            cart.setSaleAttrValueEntityList(saleAttrValueResp.getData());
            // 查询营销信息 TODO
            Resp<List<ItemSkuSaleVO>> sale = this.gmallSmsClient.querySkuSaleBySkuId(skuId);
            List<ItemSkuSaleVO> saleVOList = sale.getData();
            cart.setSales(saleVOList);

            //查询库存信息
            Resp<List<WareSkuEntity>> wareSkuBySkuId = this.gmallWmsClient.queryWareSkuBySkuId(skuId);
            List<WareSkuEntity> wareEntityList = wareSkuBySkuId.getData();
            if(!CollectionUtils.isEmpty(wareEntityList)){
                //如果库存不为空则设置
                cart.setStore(wareEntityList.stream().anyMatch(wareSkuEntity -> wareSkuEntity.getStock()>0));
            }

            //价格同步,redis特性有就更新，没有就新增
            this.redisTemplate.opsForValue().set(CURRENT_PRICE_PREFIX+skuId,skuInfoEntity.getPrice().toString());
        }
        //重新写入redis
        hashOps.put(skuId.toString(),JSON.toJSONString(cart));
    }

    /**
     * 查询购物车
     * @return
     */
    public List<Cart> queryCarts() {
        List<Cart> unLoginCarts=null;
        //获取登录状态
        UserInfo userInfo=LoginInterceptor.getUserInfo();
        //查询未登录的购物车
        String unLoginKey = CART_PREFIX + userInfo.getUserKey();//未登录的key
        BoundHashOperations<String, Object, Object> userKeyOps = this.redisTemplate.boundHashOps(unLoginKey);
        List<Object> cartJsonList = userKeyOps.values();//获得的是<skuId,cart>
        if(!CollectionUtils.isEmpty(cartJsonList)){
            unLoginCarts=cartJsonList.stream().map(cartJson -> {
                Cart cart=JSON.parseObject(cartJson.toString(),Cart.class);
                //查询当前价格
                String priceString = this.redisTemplate.opsForValue().get(CURRENT_PRICE_PREFIX + cart.getSkuId());
                cart.setCurrentPrice(new BigDecimal(priceString));
                return cart;
            }).collect(Collectors.toList());

        }

        //判断是否登录，未登录，直接返回
        if(userInfo.getId()==null){
            return unLoginCarts;
        }
        //登录，购物车同步
        String loginKey=CART_PREFIX+userInfo.getId();//登录的key
        BoundHashOperations<String, Object, Object> loginHashOps=this.redisTemplate.boundHashOps(loginKey);
        // 如果未登录状态的购物车不为空，需要合并
        if(!CollectionUtils.isEmpty(unLoginCarts)){
            unLoginCarts.forEach(cart -> {
                Integer count = cart.getCount();
                Long skuId = cart.getSkuId();
                // 购物车已存在该记录，更新数量
                if(loginHashOps.hasKey(skuId.toString())){
                    String cartJson = loginHashOps.get(cart.getSkuId().toString()).toString();
                    cart = JSON.parseObject(cartJson, Cart.class);
                    cart.setCount(cart.getCount()+count);
                }
                //// 购物车不存在该记录，新增记录
                loginHashOps.put(skuId.toString(),JSON.toJSONString(cart));
            });
            // 合并完成后，删除未登录的购物车
            this.redisTemplate.delete(unLoginKey);
        }

        //查询登录装太的购物车
        List<Object> loginCartJsonList=loginHashOps.values();
        if(!CollectionUtils.isEmpty(loginCartJsonList)){
            return loginCartJsonList.stream().map(cartJson->{
                    Cart cart=JSON.parseObject(cartJson.toString(),Cart.class);
                    //查询当前价格
                    String priceString = this.redisTemplate.opsForValue().get(CURRENT_PRICE_PREFIX + cart.getSkuId());
                    cart.setCurrentPrice(new BigDecimal(priceString));
                    return cart;
            }).collect(Collectors.toList());
        }
        return null;
    }

    /**
     * 修改购物车
     * @param cart
     */
    public void updateCart(Cart cart) {

        String key=CART_PREFIX;

        //获取登录状态
        UserInfo userInfo = LoginInterceptor.getUserInfo();
        if(userInfo.getId()!=null){
            key+=userInfo.getId();
        }else{
            key+=userInfo.getUserKey();
        }
        // 获取hash操作对象
        //获取购物车
        BoundHashOperations<String, Object, Object> hashOperations = this.redisTemplate.boundHashOps(key);
        String skuId = cart.getSkuId().toString();
        Integer count = cart.getCount();
        //判断更新的这条记录，在购物车里面有没有
        if(hashOperations.hasKey(skuId)){

            //获取购物车信息
            String cartJson = hashOperations.get(skuId).toString();
            cart = JSON.parseObject(cartJson, Cart.class);
            //更新数量
            cart.setCount(count);
//            //查询当前价格
//            String priceString = this.redisTemplate.opsForValue().get(CURRENT_PRICE_PREFIX + cart.getSkuId());
//            cart.setCurrentPrice(new BigDecimal(priceString));
            hashOperations.put(cart.getSkuId().toString(), JSON.toJSONString(cart));
        }
    }

    /**
     * 删除购物车
     * @param skuId
     */
    public void deleteCart(Long skuId) {

        String key=CART_PREFIX;

        //获取登录状态
        UserInfo userInfo = LoginInterceptor.getUserInfo();
        if(userInfo.getId()!=null){
            key+=userInfo.getId();
        }else{
            key+=userInfo.getUserKey();
        }
        BoundHashOperations<String, Object, Object> hashOperations = this.redisTemplate.boundHashOps(key);
        if(hashOperations.hasKey(skuId.toString())){
            hashOperations.delete(skuId.toString());
        }
    }

    /**
     * 根据用户ID查询已登录购物车
     * @param userId
     * @return
     */
    public List<Cart> queryCheckCartsByUserId(Long userId) {
        String key=CART_PREFIX;
        BoundHashOperations<String, Object, Object> hashOps = this.redisTemplate.boundHashOps(key + userId);
        List<Object> cartJsonList = hashOps.values();
        return cartJsonList.stream().map(cartJson ->
                JSON.parseObject(cartJson.toString(), Cart.class))
                //过滤，获取已经选中的购物车
                .filter(Cart::getCheck).collect(Collectors.toList());
    }
}
